import { createSlice, PayloadAction, createAsyncThunk } from "@reduxjs/toolkit"
import axios from "axios"
import { BASE_URL } from "../../config"
interface ProductDetailState {
  loading: boolean
  error: string | null
  data: any
}

const initialState: ProductDetailState = {
  loading: true,
  error: null,
  data: null,
}

export const getProductDetail = createAsyncThunk(
  "productDetail/getProductDetail",
  async (touristRouteId: string, thunkAPI) => {
    // thunkAPI.dispatch(productDetailSlice.actions.fetchStart())
    // try {
    const {
      data: { data },
    } = await axios.get(`${BASE_URL}/touristRoutes/${touristRouteId}`)
    return data
    //   thunkAPI.dispatch(productDetailSlice.actions.fetchSuccess(data))
    // } catch (error) {
    //   thunkAPI.dispatch(productDetailSlice.actions.fetchError(error.message))
    // }
  }
)
// 通过createSlice一次性定义 action 和 reducer
export const productDetailSlice = createSlice({
  name: "productDetail",
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder.addCase(getProductDetail.pending.type, (state, action) => {
      state.loading = true
    })
    builder.addCase(
      getProductDetail.fulfilled.type,
      (state, action: PayloadAction<string | null>) => {
        state.loading = false
        state.data = action.payload
        state.error = null
      }
    )
    builder.addCase(
      getProductDetail.rejected.type,
      (state, action: PayloadAction<string | null>) => {
        state.loading = false
        state.error = action.payload
      }
    )
  },
})
